﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using InventoryManagement;
using MII_FIF.Common;

namespace MII_FIF.Layouts.MII_FIF
{
    public partial class FormNetworkDevice : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Generic.IsUserInGroup(Configuration.DeviceManagementGroupName))
            {
                ((Label)Header.FindControl("lblHeader")).Text = "Device Management - Form Network Device";
                if (!IsPostBack)
                {
                    ViewState["EditMode"] = false;
                    if (Request.QueryString["ID"] != null)
                    {
                        ViewState["ID"] = Request.QueryString["ID"].ToString();
                        ViewState["EditMode"] = true;
                    }
                    Initialize();
                }
            }
            else
            {
                Response.Redirect(Generic.GenLink("/"));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/DeviceManagement/ViewNetworkDevice.aspx"));
        }

        void Initialize()
        {
            #region BindDDL
            System_Brand brand = new System_Brand();
            brand.IsDeleted = false;
            DataTable brandColl = brand.SelectByParam();
            Generic.BindDDL(ddlSystemBrand, brandColl, System_Brand_Fields.Title.ToString(), System_Brand_Fields.ID.ToString());
            /*
            System_Type type = new System_Type();
            type.IsDeleted = false;
            DataTable typeColl = type.SelectByParam();
            Generic.BindDDL(ddlSystemType, typeColl, System_Type_Fields.Title.ToString(), System_Type_Fields.ID.ToString());
             */
            Location location = new Location();
            location.IsDeleted = false;
            DataTable dtLocation = location.SelectByParam();
            Generic.BindDDL(ddlLocation, dtLocation, Location_Fields.Lokasi.ToString(), Location_Fields.ID.ToString());
            Rack_Number rackNumber = new Rack_Number();
            rackNumber.IsDeleted = false;
            DataTable dtRackNumber = rackNumber.SelectByParam();
            Generic.BindDDL(ddlRackNumber, dtRackNumber, Rack_Number_Fields.Title.ToString(), Rack_Number_Fields.ID.ToString());
            #endregion

            ViewState["valid"] = true;
            // check for ID in request
            if (Request.QueryString["ID"] != null)
            {
                Guid ID = Guid.Empty;
                if (Guid.TryParse(Request.QueryString["ID"], out ID))
                {
                    Inventory_Network invNetwork = new Inventory_Network();
                    invNetwork.ID = ID;
                    invNetwork.Select();
                    lblInventoryBy.Text = invNetwork.InventoryBy;
                    ddlRackNumber.SelectedValue = invNetwork.ID_RackNumber.ToString();
                    txtLabelName.Text = invNetwork.LabelName;
                    ddlLocation.SelectedValue = invNetwork.ID_DataCabang.ToString();
                    rblSystemClass.SelectedIndex = rblSystemClass.Items.IndexOf(rblSystemClass.Items.FindByValue(invNetwork.SystemClass));
                    ddlStartFrom.SelectedValue = invNetwork.StartFrom;
                    ddlSystemBrand.SelectedValue = invNetwork.ID_SysBrand.ToString();
                    ddlSystemBrand_SelectedIndexChanged(this, EventArgs.Empty);
                    ddlSystemType.SelectedValue = invNetwork.ID_SysType.ToString();
                    txtIP.Text = invNetwork.IP;
                    txtHostName.Text = invNetwork.HostName;
                    txtPathNumber.Text = invNetwork.PathNumber;
                    txtSerialNumber.Text = invNetwork.SerialNumber;
                    txtLANPort.Text = invNetwork.LANPort.ToString();
                    txtWANPort.Text = invNetwork.WANPort.ToString();
                    txtFirmwareVersion.Text = invNetwork.FirmwareVersion;
                    txtNotes.Text = invNetwork.Notes;
                    ViewState["Link"] = invNetwork.URLAttachment;

                    Modul_Detail detail = new Modul_Detail();
                    detail.ID_Network = ID;
                    DataTable dtModul = detail.SelectByParam();                
                    GridModul.DataSource = dtModul;
                    GridModul.DataBind();
                    ViewState["dtModul"] = dtModul;
                    ViewState["dtModulEdit"] = dtModul;

                    string filename = Generic.GetFileNameFromUrl(invNetwork.URLAttachment);
                    lblFileName.Text = filename;
                    btnDownload.Visible = !string.IsNullOrEmpty(filename);
                    lblFileName.Visible = !string.IsNullOrEmpty(filename);
                    FUAttachment.Visible = false;
                }
            }
            else
            {
                lblInventoryBy.Text = SPContext.Current.Web.CurrentUser.Name;

                DataTable dtModul = new DataTable();
                dtModul.Columns.Add(new DataColumn("ModulName", typeof(string)));
                dtModul.Columns.Add(new DataColumn("PathNumber", typeof(string)));
                dtModul.Columns.Add(new DataColumn("SerialNumber", typeof(string)));
                dtModul.Columns.Add(new DataColumn("SlotName", typeof(string)));
                dtModul.Columns.Add(new DataColumn("ID", typeof(string)));
                GridModul.DataSource = dtModul;
                GridModul.DataBind();
                ViewState["dtModul"] = dtModul;
             
                btnDownload.Visible = false;
                lblFileName.Visible = false;
                FUAttachment.Visible = true;
            }
        }

        bool validasi()
        {
            bool check = true;
            lblerror.Text = string.Empty;
            if (!(bool)ViewState["EditMode"])
            {
                /*
                if (!FUAttachment.HasFile)
                {
                    lblerror.Text += "Please upload attachment. <br />"; check = false;
                }
                else */
                if (Generic.checkUploadedFileName(FUAttachment.FileName))
                {
                    lblerror.Text += "Uploaded file name cannot contains # % & * : < > ? /  { | } <br />"; check = false;
                }
            }            
            return check;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (validasi())
            {
                Inventory_Network invNetwork = new Inventory_Network();
                invNetwork.InventoryBy = lblInventoryBy.Text;
                invNetwork.ID_RackNumber = StringUtil.ToGuid(ddlRackNumber.SelectedValue);
                invNetwork.LabelName = txtLabelName.Text;
                invNetwork.ID_DataCabang = StringUtil.ToGuid(ddlLocation.SelectedValue);
                invNetwork.SystemClass = rblSystemClass.SelectedValue;
                invNetwork.StartFrom = ddlStartFrom.SelectedValue;
                invNetwork.ID_SysBrand = StringUtil.ToGuid(ddlSystemBrand.SelectedValue);
                invNetwork.ID_SysType = StringUtil.ToGuid(ddlSystemType.SelectedValue);
                invNetwork.IP = txtIP.Text;
                invNetwork.HostName = txtHostName.Text;
                invNetwork.PathNumber = txtPathNumber.Text;
                invNetwork.SerialNumber = txtSerialNumber.Text;
                invNetwork.LANPort = StringUtil.ToInt32(txtLANPort.Text);
                invNetwork.WANPort = StringUtil.ToInt32(txtWANPort.Text);
                invNetwork.FirmwareVersion = txtFirmwareVersion.Text;
                invNetwork.Notes = txtNotes.Text;
                invNetwork.InventoryDate = DateTime.Now;
                invNetwork.IsDeleted = false;

                if (Request.QueryString["ID"] != null)
                {
                    Guid ID = Guid.Empty;
                    if (Guid.TryParse(Request.QueryString["ID"], out ID))
                    {
                        invNetwork.URLAttachment = ViewState["Link"] as string;
                        invNetwork.ID = ID;
                        invNetwork.Update();
                        using (DataTable dtModul = ViewState["dtModulEdit"] as DataTable)
                        {
                            foreach (DataRow row in dtModul.Rows)
                            {
                                Modul_Detail modul = new Modul_Detail();
                                modul.ID = new Guid(row["ID"].ToString());
                                modul.Delete();
                            }
                        }

                        using (DataTable dtModul = ViewState["dtModul"] as DataTable)
                        {
                            foreach (DataRow row in dtModul.Rows)
                            {
                                Modul_Detail modul = new Modul_Detail();
                                modul.ID = new Guid(row["ID"].ToString());
                                modul.ID_Network = ID;
                                modul.ModulName = row["ModulName"].ToString();
                                modul.PathNumber = row["PathNumber"].ToString();
                                modul.SerialNumber = row["SerialNumber"].ToString();
                                modul.SlotName = row["SlotName"].ToString();
                                modul.Insert();
                            }
                            ViewState["dtModulEdit"] = dtModul;
                        }
                    }
                }
                else
                {
                    invNetwork.URLAttachment = Generic.UploadFile(FUAttachment);

                    Guid ID = Guid.NewGuid();
                    invNetwork.ID = ID;
                    invNetwork.Insert();
                    using (DataTable dtModul = (DataTable)ViewState["dtModul"])
                    {
                        foreach (DataRow row in dtModul.Rows)
                        {
                            Modul_Detail modul = new Modul_Detail();
                            modul.ID = new Guid(row["ID"].ToString());
                            modul.ID_Network = ID;
                            modul.ModulName = row["ModulName"].ToString();
                            modul.PathNumber = row["PathNumber"].ToString();
                            modul.SerialNumber = row["SerialNumber"].ToString();
                            modul.SlotName = row["SlotName"].ToString();
                            modul.Insert();
                        }
                    }
                }
                Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/DeviceManagement/ViewNetworkDevice.aspx"));
            }
        }

        #region GridModul
        protected void GridModul_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            DataTable dtModul = ViewState["dtModul"] as DataTable;
            dtModul.Rows[e.RowIndex]["ModulName"] = ((TextBox)GridModul.Rows[e.RowIndex].FindControl("txtModulName")).Text;
            dtModul.Rows[e.RowIndex]["PathNumber"] = ((TextBox)GridModul.Rows[e.RowIndex].FindControl("txtModulPathNumber")).Text;
            dtModul.Rows[e.RowIndex]["SerialNumber"] = ((TextBox)GridModul.Rows[e.RowIndex].FindControl("txtModulSerialNumber")).Text;
            dtModul.Rows[e.RowIndex]["SlotName"] = ((TextBox)GridModul.Rows[e.RowIndex].FindControl("txtModulSlotName")).Text;
            GridModul.EditIndex = -1;
            GridModul.DataSource = dtModul;
            GridModul.DataBind();
            ViewState["dtModul"] = dtModul;
            btnAdd.Enabled = true;
            btnDelete.Enabled = true;
            btnCancel.Enabled = true;
            btnSubmit.Enabled = true;
        }

        protected void GridModul_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridModul.EditIndex = -1;
            GridModul.DataSource = ViewState["dtModul"] as DataTable;
            GridModul.DataBind();
            btnAdd.Enabled = true;
            btnDelete.Enabled = true;
            btnCancel.Enabled = true;
            btnSubmit.Enabled = true;
        }

        protected void GridModul_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridModul.EditIndex = e.NewEditIndex;
            GridModul.DataSource = ViewState["dtModul"] as DataTable;
            GridModul.DataBind();

            btnAdd.Enabled = false;
            btnDelete.Enabled = false;
            btnCancel.Enabled = false;
            btnSubmit.Enabled = false;
        }

        protected void GridModul_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridModul.PageIndex = e.NewPageIndex;
            GridModul.DataSource = ViewState["dtModul"] as DataTable;
            GridModul.DataBind();
        }
        #endregion

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            DataTable dtModul = (DataTable)ViewState["dtModul"];
            DataRow row = dtModul.NewRow();
            row["ModulName"] = txtModulName.Text;
            row["PathNumber"] = txtModulPathNumber.Text;
            row["SerialNumber"] = txtModulSerialNumber.Text;
            row["SlotName"] = txtModulSlotName.Text;
            row["ID"] = Guid.NewGuid();
            dtModul.Rows.Add(row);

            GridModul.DataSource = dtModul;
            GridModul.DataBind();
            ViewState["dtModul"] = dtModul;
            txtModulName.Focus();
        }        

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            bool delete = false;
            DataTable dtModul = ViewState["dtModul"] as DataTable;
            foreach (GridViewRow row in GridModul.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chk");
                if (chk != null)
                    if (chk.Checked)
                    {
                        delete = true;
                    }
            }
            if (delete)
            {
                for (int i = GridModul.Rows.Count - 1; i > -1; i--)
                {
                    CheckBox chk = (CheckBox)GridModul.Rows[i].FindControl("chk");
                    if (chk != null)
                        if (chk.Checked)
                        {
                            dtModul.Rows.RemoveAt(i + GridModul.PageIndex * GridModul.PageSize);
                        }
                }
                GridModul.DataSource = dtModul;
                GridModul.DataBind();
                ViewState["dtModul"] = dtModul;
            }
        }        

        protected override void OnPreRender(EventArgs e)
        {

            string script =
                           "function download() {" +
                           "var link ='" + ViewState["Link"] + "';" +
                           "var retvalue = window.open('" + Generic.GenLink("/_layouts/MII_FIF/Download.aspx") + "?links=' + link"
                         + ", '', 'width=1000,height=1000');}";

            Page.ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), "opendownload", script, true);
        }

        protected void ddlSystemBrand_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateSystemType();
        }

        void UpdateSystemType()
        {
            if (!ddlSystemBrand.SelectedValue.Equals("-1"))
            {
                System_Type type = new System_Type();
                type.ID_SystemBrand = StringUtil.ToGuid(ddlSystemBrand.SelectedValue);
                DataTable datatable = type.SelectByParam();
                Generic.BindDDL(ddlSystemType, datatable, System_Type_Fields.Title.ToString(), System_Type_Fields.ID.ToString());
                ddlSystemBrand.Focus();
            }
        }
    }
}
